<script setup lang="ts">
import CustomNavbar from './components/CustomNavbar.vue'
import XtxSwiper from '@/components/XtxSwiper.vue'
import type { BannerItem, CategoryItem } from '@/types/home'
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getHomeBannerAPI, getHomeCategoryAPI } from '@/services/home'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'

import type { XtxGuessInstance } from '@/types/components'
import Skeleton from './components/skeleton.vue'
import XtxGuess from '@/components/XtxGuess.vue'

const bannerList = ref<BannerItem[]>([])
const categoryList = ref<CategoryItem[]>([])
const loading = ref<boolean>(true)
// 页面加载
onLoad(async () => {
  loading.value = true
  await Promise.all([getHomeBanner(), getHomeCategory()])
  loading.value = false
})

const getHomeBanner = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

const getHomeCategory = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

// 获取猜你喜欢组件实例
const guessRef = ref<XtxGuessInstance>()

// 滚动触底事件
const onScrolltolower = () => {
  guessRef.value?.getMore()
}

// 下拉刷新状态
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 重置猜你喜欢组件数据
  guessRef.value?.resetData() // 加载数据
  await Promise.all([getHomeBanner(), getHomeCategory()]) // 关闭动画
  isTriggered.value = false
}
</script>

<template>
  <view class="index">
    <CustomNavbar />
    <Skeleton v-if="loading" />
    <template v-else>
      <scroll-view
        refresher-enabled
        @refresherrefresh="onRefresherrefresh"
        :refresher-triggered="isTriggered"
        class="scroll-view"
        scroll-y
        @scrolltolower="onScrolltolower"
      >
        <XtxSwiper :list="bannerList" />
        <CategoryPanel :list="categoryList" />
        <HotPanel />
        <XtxGuess ref="guessRef" />
      </scroll-view>
    </template>
  </view>
</template>

<style lang="scss">
.index {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
